<template>
  <p-modal
    v-if="visible"
    v-model="visible"
    :title="title"
    :width="1050"
    :mask-closable="false"
    style="height: 600px;"
    @cancel="handleCancel"
  >
    <div class="modal-box">
      <p-form-model ref="fuleForm" layout="inline" :model="form" :rules="rules">
        <TitleSecondary title="基本信息" />
        <div v-if="(!showCustomerCreate && !formInfo.accordPrivacy && !showDetail && addCustomer) || showDetail">
          <div class="view">
            <div class="left">
              <p-form-model-item label="姓名" prop="" style="width: 100%;">
                {{ form.name }}
              </p-form-model-item>
              <p-form-model-item label="职级" prop="" style="width: 100%;">
                {{ rankCodeObj[form.rankCode] }}
              </p-form-model-item>
              <p-form-model-item label="职位" prop="" style="width: 100%;">
                {{ form.position }}
              </p-form-model-item>
              <p-form-model-item label="邮箱" prop="" style="width: 100%;">
                {{ form.email }}
              </p-form-model-item>
              <p-form-model-item label="客户" prop="" style="width: 100%;">
                {{ name }}
              </p-form-model-item>
              <p-form-model-item label="性别" prop="" style="width: 100%;">
                {{ genderObj[form.gender] }}
              </p-form-model-item>
              <p-form-model-item
                label="上一级联系人"
                prop=""
                style="width: 100%;"
              >
                {{ form.higherLevelName }}
              </p-form-model-item>
              <p-form-model-item
                v-if="formInfo.accordPrivacy"
                label="学历"
                prop=""
                style="width: 100%;"
              >
                {{ educationOptionsView[form.education] }}
              </p-form-model-item>
            </div>
            <div class="right">
              <p-form-model-item label="联系电话" prop="" style="width: 100%;">
                {{ form.tel }}
              </p-form-model-item>

              <p-form-model-item label="业务线" prop="" style="width: 100%;">
                {{ professionIdOptionsView[form.professionId] }}
              </p-form-model-item>

              <p-form-model-item label="部门" prop="" style="width: 100%;">
                {{ form.department }}
              </p-form-model-item>

              <p-form-model-item
                v-if="formInfo.accordPrivacy"
                label="生日"
                prop=""
                style="width: 100%;"
              >
                {{ form.birthday }}
              </p-form-model-item>

              <p-form-model-item label="国籍" prop="" style="width: 100%;">
                {{ form.country }}
              </p-form-model-item>

              <p-form-model-item label="民族" prop="" style="width: 100%;">
                {{ form.clan }}
              </p-form-model-item>

              <p-form-model-item label="状态" prop="" style="width: 100%;">
                {{ contactStatus[form.contactStatus] }}
              </p-form-model-item>
            </div>
          </div>

          <p-form-model-item
            v-if="formInfo.accordPrivacy"
            label="兴趣爱好"
            prop=""
            style="width: 100%;"
          >
            {{ form.hobby }}
          </p-form-model-item>
          <p-form-model-item
            v-if="formInfo.accordPrivacy"
            label="家庭地址"
            prop=""
            style="width: 100%;"
          >
            {{ form.address }}
          </p-form-model-item>

          <p-form-model-item label="毕业院校" prop="" style="width: 100%;">
            {{ form.graduatedSchool }}
          </p-form-model-item>
          <p-form-model-item label="从业经历" prop="" style="width: 100%;">
            {{ form.experience }}
          </p-form-model-item>
          <p-form-model-item
            v-if="formInfo.accordPrivacy"
            label="口味偏好"
            prop=""
            style="width: 100%;"
          >
            {{ form.tastePreference }}
          </p-form-model-item>
          <!-- <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="姓名" prop="" style="width: 100%;">
                {{ form.name }}
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="联系电话" prop="" style="width: 100%;">
                {{ form.tel }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="职级" prop="" style="width: 100%;">
                {{ rankCodeObj[form.rankCode] }}
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="业务线" prop="" style="width: 100%;">
                {{ professionIdOptionsView[form.professionId] }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="职位" prop="" style="width: 100%;">
                {{ form.position }}
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="部门" prop="" style="width: 100%;">
                {{ form.department }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="邮箱" prop="" style="width: 100%;">
                {{ form.email }}
              </p-form-model-item>
            </p-col>
            <p-col v-if="formInfo.accordPrivacy" :span="12" style="height: 56px;">
              <p-form-model-item label="生日" prop="" style="width: 100%;">
                {{ form.birthday }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="客户" prop="" style="width: 100%;">
                {{ name }}
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="国籍" prop="" style="width: 100%;">
                {{ form.country }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="性别" prop="" style="width: 100%;">
                {{ genderObj[form.gender] }}
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="民族" prop="" style="width: 100%;">
                {{ form.clan }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="上一级联系人" prop="" style="width: 100%;">
                {{ form.higherLevelName }}
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="状态" prop="" style="width: 100%;">
                {{ contactStatus[form.contactStatus] }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col v-if="formInfo.accordPrivacy" :span="24">
              <p-form-model-item label="兴趣爱好" prop="" style="width: 100%;">
                {{ form.hobby }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col v-if="formInfo.accordPrivacy" :span="24">
              <p-form-model-item label="家庭地址" prop="" style="width: 100%;">
                {{ form.address }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col v-if="formInfo.accordPrivacy" :span="12" style="height: 56px;">
              <p-form-model-item label="学历" prop="" style="width: 100%;">
                {{ educationOptionsView[form.education] }}
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="毕业院校" prop="" style="width: 100%;">
                {{ form.graduatedSchool }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="24">
              <p-form-model-item label="从业经历" prop="" style="width: 100%;">
                {{ form.experience }}
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col v-if="formInfo.accordPrivacy" :span="24">
              <p-form-model-item label="口味偏好" prop="" style="width: 100%;">
                {{ form.tastePreference }}
              </p-form-model-item>
            </p-col>
          </p-row> -->
        </div>
        <div v-else class="business-box">
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="姓名" prop="name" style="width: 100%;">
                <p-input v-model="form.name" placeholder="请输入" />
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="联系电话"
                prop="tel"
                style="width: 100%;"
              >
                <p-input v-model="form.tel" placeholder="请输入" />
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="职级"
                prop="rankCode"
                style="width: 100%;"
              >
                <p-select
                  :value="form.rankCode"
                  placeholder="请选择"
                  :get-popup-container="
                    triggerNode => triggerNode.parentNode || document.body
                  "
                  @change="handleSelectChange($event, 'rankCode')"
                >
                  <p-select-option
                    v-for="item in rankCodeOptions"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </p-select-option>
                </p-select>
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="业务线"
                prop="professionId"
                style="width: 100%;"
              >
                <p-select
                  :value="form.professionId"
                  placeholder="请选择"
                  :get-popup-container="
                    triggerNode => triggerNode.parentNode || document.body
                  "
                  :disabled="isProfessionId"
                  @change="handleSelectChange($event, 'professionId')"
                >
                  <p-select-option
                    v-for="item in professionIdOptions"
                    :key="item.id"
                    :value="item.id"
                    :disabled="professionIdDisabled(item.state)"
                  >
                    {{ item.professionName }}
                  </p-select-option>
                </p-select>
                <div v-show="rankCodeRutes.isShow" class="waring">
                  {{ rankCodeRutes.text }}
                </div>
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="职位"
                prop="position"
                style="width: 100%;"
              >
                <p-input v-model="form.position" placeholder="请输入" />
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="部门"
                prop="department"
                style="width: 100%;"
              >
                <p-input v-model="form.department" placeholder="请输入" />
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="邮箱" prop="email" style="width: 100%;">
                <p-input v-model="form.email" placeholder="请输入" />
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <!-- <p-form-model-item label="传真" prop="street">
              <p-input
                v-model="form.street"
                placeholder="请输入"
              
              />
            </p-form-model-item> -->
              <p-form-model-item
                label="生日"
                prop="birthday"
                style="width: 100%;"
              >
                <p-date-picker
                  :value="form.birthday"
                  placeholder="请选择"
                  format="YYYY/MM/DD"
                  @change="handleSelectChange($event, 'birthday')"
                />
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="客户" prop="" style="width: 100%;">
                <span>{{ name }}</span>
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="国籍"
                prop="country"
                style="width: 100%;"
              >
                <p-select
                  :value="form.country"
                  placeholder="请选择"
                  :get-popup-container="
                    triggerNode => triggerNode.parentNode || document.body
                  "
                  @change="handleSelectChange($event, 'country')"
                >
                  <p-select-option
                    v-for="item in countryOptions"
                    :key="item.cn"
                    :value="item.cn"
                  >
                    {{ item.cn }}
                  </p-select-option>
                </p-select>
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="性别"
                prop="gender"
                style="width: 100%;"
              >
                <p-radio-group v-model="form.gender">
                  <p-radio :value="0">男</p-radio>
                  <p-radio :value="1">女</p-radio>
                </p-radio-group>
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item label="民族" prop="clan" style="width: 100%;">
                <p-select
                  :value="form.clan"
                  placeholder="请选择"
                  :disabled="isDisabledInfo"
                  :get-popup-container="
                    triggerNode => triggerNode.parentNode || document.body
                  "
                  @change="handleSelectChange($event, 'clan')"
                >
                  <p-select-option
                    v-for="item in clanOptions"
                    :key="item.name"
                    :value="item.name"
                  >
                    {{ item.name }}
                  </p-select-option>
                </p-select>
              </p-form-model-item>
            </p-col>
          </p-row>

          <p-form-model-item
            label="上一级联系人"
            prop="higherLevelId"
            style="width: 50%;"
          >
            <p-select
              :value="form.higherLevelId"
              placeholder="请选择"
              :get-popup-container="
                triggerNode => triggerNode.parentNode || document.body
              "
              :disabled="!higherLevelOption.length"
              @change="handleHigherLevelIdChange"
            >
              <p-select-option
                v-for="item in higherLevelIdOptions"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </p-select-option>
            </p-select>
          </p-form-model-item>
          <p-form-model-item label="兴趣爱好" prop="hobby" style="width: 100%;">
            <p-textarea
              v-model="form.hobby"
              style="overflow-y: auto;"
              placeholder="请输入"
              :auto-size="{ minRows: 3, maxRows: 3 }"
            />
            <div v-show="hobbyRutes.isShow" class="waring">
              {{ hobbyRutes.text }}
            </div>
          </p-form-model-item>
          <p-form-model-item
            label="家庭地址"
            prop="address"
            style="width: 100%;"
          >
            <p-textarea
              v-model="form.address"
              style="overflow-y: auto;"
              placeholder="请输入"
              :auto-size="{ minRows: 3, maxRows: 3 }"
            />
            <div v-show="addressRutes.isShow" class="waring">
              {{ addressRutes.text }}
            </div>
          </p-form-model-item>
          <p-row>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="学历"
                prop="education"
                style="width: 100%;"
              >
                <p-select
                  :value="form.education"
                  placeholder="请选择"
                  :get-popup-container="
                    triggerNode => triggerNode.parentNode || document.body
                  "
                  @change="handleSelectChange($event, 'education')"
                >
                  <p-select-option
                    v-for="item in educationOptions"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </p-select-option>
                </p-select>
              </p-form-model-item>
            </p-col>
            <p-col :span="12" style="height: 56px;">
              <p-form-model-item
                label="毕业院校"
                prop="graduatedSchool"
                style="width: 100%;"
              >
                <p-input v-model="form.graduatedSchool" placeholder="请输入" />
              </p-form-model-item>
            </p-col>
          </p-row>
          <p-form-model-item
            label="从业经历"
            prop="experience"
            style="width: 100%;"
          >
            <p-textarea
              v-model="form.experience"
              style="overflow-y: auto;"
              placeholder="请输入"
              :auto-size="{ minRows: 3, maxRows: 3 }"
            />
            <div v-show="experienceRutes.isShow" class="waring">
              {{ experienceRutes.text }}
            </div>
          </p-form-model-item>
          <p-form-model-item
            label="口味偏好"
            prop="tastePreference"
            style="width: 100%;"
          >
            <p-textarea
              v-model="form.tastePreference"
              style="overflow-y: auto;"
              placeholder="请输入"
              :auto-size="{ minRows: 3, maxRows: 3 }"
            />
            <div v-show="tastePreferenceRutes.isShow" class="waring">
              {{ tastePreferenceRutes.text }}
            </div>
          </p-form-model-item>
        </div>
      </p-form-model>
      <TitleSecondary title="家庭成员" />
      <ButtonGroup
        v-if="showTableBtn"
        class="top"
        :options="topButtons"
        @click="handleButtonClick"
      />
      <p-table
        v-if="showTable"
        :custom-header-row="customHeaderRowMinxin"
        row-key="id"
        :columns="columns"
        bordered
        :loading="loading"
        :scroll="{ x: '100%', y: 250 }"
        :data-source="dataSource"
        :pagination="false"
        :row-selection="getRowSelection"
        @change="handleTableChange"
      >
        <template slot="relationCode" slot-scope="text, record, index">
          <SelectCustomer
            :value="text"
            :has-all="false"
            :is-edit="isEditFamilies"
            :options="relationCodeOptions"
            :select-type="selectType"
            :allow-clear="false"
            @input="
              handleInputChange($event, text, record, index, 'relationCode')
            "
          />
        </template>
        <template slot="name" slot-scope="text, record, index">
          <InputDefault
            :value="text"
            :is-edit="isEditFamilies"
            @change="handleInputChange($event, text, record, index, 'name')"
          />
        </template>
        <template slot="companyName" slot-scope="text, record, index">
          <InputDefault
            :value="text"
            :is-edit="isEditFamilies"
            @change="
              handleInputChange($event, text, record, index, 'companyName')
            "
          />
        </template>
        <template slot="position" slot-scope="text, record, index">
          <InputDefault
            :value="text"
            :is-edit="isEditFamilies"
            @change="handleInputChange($event, text, record, index, 'position')"
          />
        </template>
        <template slot="tel" slot-scope="text, record, index">
          <InputDefault
            :value="text"
            :is-edit="isEditFamilies"
            @change="handleInputChange($event, text, record, index, 'tel')"
          />
        </template>
      </p-table>
      <TitleSecondary
        v-if="showDetail"
        title="层级关系图"
        style="margin-top: 12px;"
      />
      <div v-if="showDetail" class="families-relation">
        <div
          v-for="(item, index) in formInfo.hierarchies"
          :key="`${index}${item.name}`"
          class="relation-box"
        >
          <div class="outer-layer">
            <div class="square">{{ item.name }}</div>
            <div class="text">{{ item.department }} {{ item.position }}</div>
            <span
              v-if="index !== formInfo.hierarchies.length - 1"
              class="line"
            ></span>
          </div>
        </div>
      </div>
    </div>
    <template v-if="showCreate" slot="footer">
      <div>
        <div v-if="showDetail" class="middle">
          <p-button type="primary" @click="handleFrozen">
            {{ getContactStatusText }}
          </p-button>
          <p-button key="submit" @click="handleCancel">关闭</p-button>
        </div>
        <div v-else-if="(!showCustomerCreate && !formInfo.accordPrivacy && !showDetail && addCustomer)">
          <p-button key="submit" @click="handleCancel">返回</p-button>
        </div>
        <div v-else class="middle">
          <p-button type="primary" @click="handleOkChange">保存</p-button>
          <p-button key="submit" @click="handleCancel">取消</p-button>
        </div>
      </div>
    </template>
    <template v-else slot="footer">
      <p-button key="submit" @click="handleCancel">返回</p-button>
    </template>
  </p-modal>
</template>

<script>
import {
  postProfessionListByPage,
  postContactInsertData,
  getCoutryList,
  getNationalList,
  postContactFamilyDelete,
  postContactUpdate,
  postContactsListByPage,
} from '@/api/customerApi.js';
import { getDicList } from '@/api/public';

import mixinTable from '@/mixins/mixin-table.js';

import monent from 'moment';
import { deepClonel } from '@/utils/index';

// let index = 0;
const createDefaultItem = () => ({
  // id: `${index++}_families`,
  // id: index++,
  relationCode: '',
  name: '',
  companyName: '',
  position: '',
  tel: '',
});

export default {
  components: {},
  mixins: [mixinTable],
  props: {
    code: {
      type: [String, Number],
      default: '',
    },
    name: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      defalut: false,
    },
    formInfo: {
      type: Object,
      default: () => ({}),
    },
    title: {
      type: String,
      default: '新增联系人',
    },
    showDetail: {
      type: Boolean,
      default: false,
    },
    showCreate: {
      type: Boolean,
      default: false,
    },
    addCustomer: {
      type: Boolean,
      default: true,
    },
    rowSelection: {
      type: Object,
      default: () => {},
    },
    isContacts: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // hierarchies: [
      //   {
      //     department: '研发部',
      //     name: '刘大哥',
      //     position: '总监'
      //   },
      //   {
      //     department: '研发部',
      //     name: '刘大哥',
      //     position: '总监'
      //   },
      // ],
      contactStatus: {
        1: '正常',
        2: '冻结',
      },
      addressRutes: {
        isShow: false,
        text: '',
      },
      rankCodeRutes: {
        isShow: false,
        text: '',
      },
      hobbyRutes: {
        isShow: false,
        text: '',
      },
      tastePreferenceRutes: {
        isShow: false,
        text: '',
      },
      experienceRutes: {
        isShow: false,
        text: '',
      },
      genderObj: {
        0: '男',
        1: '女',
      },
      higherLevelOption: [],
      higherLevelIdOptions: [],
      dataSource: [],
      listSoure: [],
      loading: false,
      form: {
        id: '',
        name: '', // 姓名
        tel: '', // 联系电话
        professionId: '', // 业务线ID
        department: '', // 部门
        position: '', // 职位
        rankCode: '', // 职级code 取自字典表
        email: '', // 邮箱
        // address: '',  // 传真。。。。。。。。。。
        birthday: undefined, // 客户生日
        gender: '', // 性别 0：男 1：女
        clan: '', // 民族
        higherLevelId: '', // 上级联系人ID
        higherLevelName: '', // 上级联系人name
        hobby: '', // 爱好
        address: '', // 家庭地址
        education: '', // 学历
        graduatedSchool: '', // 毕业学校
        country: '', // 国籍
        tastePreference: '', // 口味偏好
        experience: '', // 从业经历
        contactStatus: '1',
      },
      professionIdOptions: [], // 业务线
      rankCodeOptions: [], // 职级
      clanOptions: [], // 民族
      educationOptions: [], // 学历
      countryOptions: [], // 国籍
      relationCodeOptions: [], // 关系
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
        ],
        department: [
          {
            required: true,
            message: '请输入部门',
            trigger: 'blur',
          },
        ],
        position: [
          {
            required: true,
            message: '请输入职位',
            trigger: 'blur',
          },
        ],
        rankCode: [
          { required: true, message: '请选择职级', trigger: 'change' },
        ],
      },
    };
  },
  computed: {
    showTableBtn() {
      // 如果是详情页
      if (this.showDetail) {
        // 如果可以编辑
        return false;
      } else {
        // 如果是潜客创建
        if (this.showCustomerCreate) {
          if (this.formInfo.accordPrivacy || (!this.formInfo.accordPrivacy && !this.addCustomer)) {
            return true;
          }
          return false;
        } else {
          // 如果可以编辑 或者点击的是新增按钮
          if (this.formInfo.accordPrivacy || !this.addCustomer) {
            return true;
          }
          return false;
        }
      }
    },
    showTable() {
      // 如果是详情页
      if (this.showDetail) {
        // 如果可以编辑
        if (this.formInfo.accordPrivacy) {
          return true;
        }
        return false;
      } else {
        // 如果是潜客创建
        if (this.showCustomerCreate) {
          if (this.formInfo.accordPrivacy || (!this.formInfo.accordPrivacy && !this.addCustomer)) {
            return true;
          }
          return false;
        } else {
          // 如果可以编辑 或者点击的是新增按钮
          if (this.formInfo.accordPrivacy || !this.addCustomer) {
            return true;
          }
          return false;
        }
      }
    },
    showCustomerCreate() {
      const route = ['/customer-creation']
      return route.includes(this.$router.currentRoute.fullPath);
    },
    educationOptionsView() {
      return this.educationOptions?.reduce((pre, cur) => {
        pre[cur.value] = cur.label;
        return pre;
      }, {});
    },
    // clanOptionsView() {
    //   return this.clanOptions?.reduce((pre, cur) => {
    //     pre[cur.id] = cur.name;
    //     return pre
    //   }, {});
    // },
    professionIdOptionsView() {
      console.log(
        this.professionIdOptions?.reduce((pre, cur) => {
          pre[cur.id] = cur.professionName;
          return pre;
        }, {})
      );
      return this.professionIdOptions?.reduce((pre, cur) => {
        pre[cur.id] = cur.professionName;
        return pre;
      }, {});
    },
    getHierarchies() {
      return this.formInfo.hierarchies || [];
    },
    isEditFamilies() {
      return this.showDetail ? false : true;
    },
    getRowSelection() {
      return this.showDetail ? this.rowSelection : this.rowSelectionMixin;
    },
    rulesHobby() {
      return (this.form.hobby && this.form.hobby?.length > 255) || false;
    },
    rulesAddress() {
      return (this.form.address && this.form.address?.length > 255) || false;
    },
    rulesTastePreference() {
      return (
        (this.form.tastePreference &&
          this.form.tastePreference?.length > 255) ||
        false
      );
    },
    rulesExperience() {
      return (
        (this.form.experience && this.form.experience?.length > 255) || false
      );
    },
    // rulesRankCode() {
    //   return this.form.rankCode === '1' || this.form.rankCode === '2';
    // },
    isProfessionId() {
      return this.form.rankCode === '1';
      // return this.form.rankCode === '1' || this.form.rankCode === '2';
    },
    isDisabledInfo() {
      return this.form.country !== '中国';
    },
    topButtons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys?.length;
      return [
        {
          key: 'add',
          label: '新增',
          type: 'primary',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          type: '',
          icon: 'delete',
          disabled,
        },
      ];
    },
    selectType() {
      return this.$store.state.dictionary.dict['relation_code'] || {};
    },
    rankCodeObj() {
      return this.$store.state.dictionary.dict['rank_code'] || {};
    },
    getContactStatusText() {
      return this.formInfo.contactStatus === 1 ? '冻结' : '解冻';
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 30,
          customRender: (t, r, index) => {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '关系',
          dataIndex: 'relationCode',
          key: 'relationCode',
          width: 80,
          required: true,
          ellipsis: true,
          scopedSlots: { customRender: 'relationCode' },
        },
        {
          align: 'center',
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
          width: 80,
          required: true,
          ellipsis: true,
          scopedSlots: { customRender: 'name' },
        },
        {
          align: 'center',
          title: '公司名称',
          dataIndex: 'companyName',
          key: 'companyName',
          width: 150,
          ellipsis: true,
          scopedSlots: { customRender: 'companyName' },
        },
        {
          align: 'center',
          title: '职位',
          dataIndex: 'position',
          key: 'position',
          width: 90,
          ellipsis: true,
          scopedSlots: { customRender: 'position' },
        },
        {
          align: 'center',
          title: '联系电话',
          dataIndex: 'tel',
          key: 'tel',
          width: 100,
          ellipsis: true,
          scopedSlots: { customRender: 'tel' },
        },
      ];
      return columns;
    },
  },
  watch: {
    formInfo: {
      async handler(val) {
        if (val) {
          this.form.id = val.id;
          this.form.name = val.name;
          this.form.tel = val.tel;
          this.form.professionId = val.professionId;
          this.form.department = val.department;
          this.form.position = val.position;
          this.form.rankCode = val.rankCode;
          this.form.email = val.email;
          this.form.birthday = val.birthday && monent(val.birthday) || undefined;
          this.form.gender = val.gender;
          this.form.clan = val.clan || '';
          this.form.higherLevelId = val.higherLevelId;
          this.form.higherLevelName = val.higherLevelName;
          this.form.hobby = val.hobby || '';
          this.form.address = val.address || '';
          this.form.education = val.education;
          this.form.graduatedSchool = val.graduatedSchool;
          this.form.country = val.country;
          this.form.tastePreference = val.tastePreference || '';
          this.form.experience = val.experience || '';
          this.form.contactStatus = val.contactStatus;
          this.dataSource = val.families || [];
          this.listSoure = deepClonel(val.families) || [];
          // console.log(this.dataSource, 'jk');
        }
      },
      deep: true,
      immediate: true,
    },
    visible: {
      async handler(val) {
        if (val) {
          await this.getCountryInfoList();
          await this.getRankCodeList();
          await this.getEducationList();
          await this.getNationaInfoList();
          await this.getRelationCodeList();
          await this.getProfessionIdList();
          await this.getList();
        }
      },
      deep: true,
      immediate: true,
    },
    'form.hobby': {
      handler(val) {
        if (!val || val?.length < 255) {
          this.hobbyRutes.isShow = false;
          this.hobbyRutes.text = '';
        }
        if (val?.length > 255) {
          this.hobbyRutes.isShow = true;
          this.hobbyRutes.text = '输入内容过长';
        }
      },
      deep: true,
    },
    'form.address': {
      handler(val) {
        if (!val || val?.length < 255) {
          this.addressRutes.isShow = false;
          this.addressRutes.text = '';
        }
        if (val?.length > 255) {
          this.addressRutes.isShow = true;
          this.addressRutes.text = '输入内容过长';
        }
      },
      deep: true,
    },
    'form.experience': {
      handler(val) {
        if (!val || val?.length < 255) {
          this.experienceRutes.isShow = false;
          this.experienceRutes.text = '';
        }
        if (val?.length > 255) {
          this.experienceRutes.isShow = true;
          this.experienceRutes.text = '输入内容过长';
        }
      },
      deep: true,
    },
    'form.tastePreference': {
      handler(val) {
        if (!val || val?.length < 255) {
          this.tastePreferenceRutes.isShow = false;
          this.tastePreferenceRutes.text = '';
        }
        if (val?.length > 255) {
          this.tastePreferenceRutes.isShow = true;
          this.tastePreferenceRutes.text = '输入内容过长';
        }
      },
      deep: true,
    },
    'form.rankCode': {
      handler(val) {
        if (val === '1' || !val) {
          this.rankCodeRutes.isShow = false;
          this.rankCodeRutes.text = '';
        } else {
          this.rankCodeRutes.isShow = true;
          this.rankCodeRutes.text = '请选择业务线';
        }
      },
      deep: true,
    },
    'form.professionId': {
      handler(val) {
        if (val) {
          this.rankCodeRutes.isShow = false;
          this.rankCodeRutes.text = '';
        }
      },
      deep: true,
    },
  },
  created() {},
  methods: {
    professionIdDisabled(state) {
      return !state;
    },
    getParams() {
      const page = {
        current: this.paginationMixin.current,
        pageSize: 1000,
        customerCode: this.code,
      };
      return page;
    },
    async getList() {
      const id = this.formInfo.id;
      const data = this.getParams();
      const result = await postContactsListByPage(data);
      const list = result?.data?.data?.records || [];
      this.higherLevelOption = list;
      this.higherLevelIdOptions = list;
      if (this.isContacts) {
        this.higherLevelIdOptions = list?.filter(item => item.id !== id);
      }
      // console.log(this.higherLevelIdOptions, 'qwe')
    },
    // 冻结、解冻
    async handleFrozen() {
      const type = this.formInfo.contactStatus === 1 ? 2 : 1;
      const res = await postContactUpdate({
        id: this.formInfo.id,
        contactStatus: type,
      });
      if (res?.data?.code === 0) {
        this.$message.success(
          `${this.formInfo.contactStatus === 1 ? '冻结' : '解冻'}成功`
        );
      } else {
        this.$message.error(
          `${this.formInfo.contactStatus === 1 ? '冻结' : '解冻'}失败`
        );
      }
      this.handleCancel();
    },
    handleInputChange(e, text, record, index, key) {
      this.dataSource[index][key] = e;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      console.log('fn: ', fn);
      this[fn] && this[fn]();
    },
    addCallback() {
      this.dataSource.push({ ...createDefaultItem() });
      console.log(this.dataSource, 'this.dataSource.');
      // console.log(this.listSoure, 'this.listSoure.');
    },
    deleteCallback() {
      let allId =
        (this.listSoure.length && this.listSoure?.map(item => item.id)) || [];
      let deleteList = this.rowSelectionMixin.selectedRowKeys || [];

      let oldList = deleteList?.filter(item => {
        return allId.includes(item);
      });

      let newList = deleteList?.filter(item => {
        return !allId.includes(item);
      });
      if (oldList.length && newList.length) {
        this.$message.error('请先保存新增的数据,再进行数据删除！');
        return;
      }
      if (newList.length) {
        newList.forEach(id => {
          const index = this.dataSource.findIndex(item => item.id === id);
          this.dataSource.splice(index, 1);
        });
        this.$message.success('删除成功');
        this.rowSelectionMixin.selectedRowKeys = [];
        return;
      }

      this.$confirm(`该操作将删除 ${deleteList.length} 条数据，是否确认？`)
        .then(async () => {
          if (oldList.length) {
            const res = await postContactFamilyDelete(oldList);
            if (res?.data?.data) {
              this.$message.success('删除成功');
              this.paginationMixin.current = 1;
              this.$emit('refresh', this.form.id);
            } else {
              this.$message.error('删除失败');
            }
            // console.log(oldList)
          }
          this.rowSelectionMixin.selectedRowKeys = [];
        })
        .catch(err => {
          console.log(err);
        });
    },
    async selectList(code) {
      const result = await getDicList(code);
      return result?.data?.data || [];
    },
    getSourceData() {
      let dataList = this.dataSource || [];
      let data = dataList?.filter(item => {
        return !item.id;
      });
      return data;
    },
    getIsValid() {
      this.rowSelectionMixin.selectedRowKeys = [];
      let data = this.getSourceData();
      const isValid = data?.every(
        item => item.relationCode && String(item.name)
      );
      if (!isValid) {
        this.$message.error('请将新增家庭成员数据填写完整！');
        return false;
      }
      return true;
    },
    async handleOkChange() {
      const valid = this.validate();
      const data = {
        ...this.form,
        birthday: monent(this.form.birthday).format('YYYY-MM-DD'),
        families: this.dataSource,
        contactStatus: 1,
      };
      // console.log(data);
      if (
        this.form.rankCode &&
        !this.isProfessionId &&
        !this.form.professionId
      ) {
        this.$message.error('请选择业务线');
        return;
      }

      if (this.rulesHobby) {
        this.$message.error('兴趣爱好输入内容过长');
        return;
      }
      if (this.rulesAddress) {
        this.$message.error('家庭地址输入内容过长');
        return;
      }
      if (this.rulesTastePreference) {
        this.$message.error('口味偏好输入内容过长');
        return;
      }
      if (this.rulesExperience) {
        this.$message.error('从业经历输入内容过长');
        return;
      }
      if (!valid) return new Promise(() => {});
      if (!this.getIsValid()) {
        return;
      }
      if (valid) {
        const result = await postContactInsertData({
          ...data,
          customerCode: this.code,
        });
        if (result?.data?.data) {
          this.$message.success('保存成功！');
          this.handleCancel();
        }
      }
    },
    handleCancel() {
      this.$emit('update:visible', false);
      this.$emit('change');
      this.form = {
        id: '',
        name: '', // 姓名
        tel: '', // 联系电话
        professionId: '', // 业务线ID
        department: '', // 部门
        position: '', // 职位
        rankCode: '', // 职级code 取自字典表
        email: '', // 邮箱
        // address: '',  // 传真。。。。。。。。。。
        birthday: undefined, // 客户生日
        gender: '', // 性别 0：男 1：女
        clan: '', // 民族
        higherLevelId: '', // 上级联系人ID
        higherLevelName: '',
        hobby: '', // 爱好
        address: '', // 家庭地址
        education: '', // 学历
        graduatedSchool: '', // 毕业学校
        country: '', // 国籍
        tastePreference: '', // 口味偏好
        experience: '', // 从业经历
      };
      this.dataSource = [];
    },
    // 业务线List
    async getProfessionIdList() {
      const res = await postProfessionListByPage({
        customerCode: this.code,
        // state: false,
      });
      const data = res?.data?.data;
      // console.log(data,'op');
      this.professionIdOptions = data || [];
      // console.log(this.professionIdOptions)
    },
    // 职级List
    async getRankCodeList() {
      const result = await this.selectList('rank_code');
      this.rankCodeOptions = result;
    },
    // 学历List
    async getEducationList() {
      const result = await this.selectList('education');
      this.educationOptions = result;
    },

    // 民族List
    async getNationaInfoList() {
      const res = await getNationalList();
      const data = res?.data?.data;
      // console.log(data,'op');
      this.clanOptions = data || [];
    },
    // 国籍List
    async getCountryInfoList() {
      const res = await getCoutryList();
      const data = res?.data?.data;
      // console.log(data,'op');
      this.countryOptions = data || [];
    },
    // 职级List
    async getRelationCodeList() {
      const result = await this.selectList('relation_code');
      this.relationCodeOptions = result;
    },
    // 上一级联系人
    handleHigherLevelIdChange(val) {
      this.form.higherLevelId = val;
      const option = this.higherLevelIdOptions?.find(item => item.id === val);
      this.form.higherLevelName = option.name;
    },
    // 选中值
    handleSelectChange(val, key) {
      // console.log(val, key)
      this.form[key] = val;
      if (key === 'rankCode') {
        this.form.professionId = '';
      }
      if (key === 'birthday') {
        this.form[key] = val;
      }
      // console.log(this.form[key], `${key}`);
      if (key === 'country' && val !== '中国') {
        this.form.clan = '';
      }
    },
    validate() {
      let validate = false;
      this.$refs.fuleForm.validate(valid => {
        validate = valid;
      });
      return validate;
    },
  },
};
</script>

<style lang="less" scoped>
.modal-box {
  height: 600px;
  overflow: auto;
  .view {
    display: flex;
  }
  .middle {
    display: flex;
    justify-content: center;
  }
  .waring {
    position: absolute;
    top: 18px;
    left: 0px;
    height: 14px;
    color: red;
    font-size: 12px;
    font-weight: 400;
  }
  .families-relation {
    margin-top: 12px;
    padding: 0 0 20px 62px;
    .outer-layer {
      position: relative;
      display: flex;
      align-items: center;
      padding-bottom: 65px;
      .square {
        width: 200px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        font-size: 12px;
        color: #040c2c;
        border: 1px solid #040c2c;
        border-radius: 2px;
        background: #ffcd9f;
      }
      .text {
        font-size: 12px;
        font-weight: 400;
        color: #040c2c;
        padding-left: 10px;
      }
      .line {
        position: absolute;
        bottom: 5px;
        left: 98px;
        display: inline-block;
        width: 2px;
        height: 46px;
        background: #040c2c;
      }
      .line::before {
        content: '';
        width: 0;
        height: 0;
        position: absolute;
        left: -4px;
        top: -20px;
        border-top: 10px solid transparent;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 10px solid black;
      }
    }
  }
}
/deep/.poros-form-item-control-wrapper {
  width: calc(100% - 150px);
}
/deep/ .poros-form-inline .poros-form-item > .poros-form-item-label {
  width: 90px;
}
/deep/.poros-form-inline .poros-form-item {
  margin-bottom: 20px;
}
// /deep/ .poros-col {
//   margin-bottom: 12px;
// }
/deep/.poros-modal-footer {
  text-align: center;
}
.top {
  margin-bottom: 15px;
}
</style>
